package com.study.socket.notblock;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/9/28 8:34
 */
public class DataGramRec
{
    public static void main(String[] args) throws IOException
    {
        DatagramChannel channel = DatagramChannel.open();
        channel.configureBlocking(false);
        channel.bind(new InetSocketAddress(9898));
        Selector selector = Selector.open();
        channel.register(selector, SelectionKey.OP_READ);
        while (selector.select() > 0)
        {
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext())
            {
                SelectionKey selectionKey = it.next();
                if (selectionKey.isReadable())
                {
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    channel.receive(byteBuffer);
                    byteBuffer.flip();
                    System.out.println(new String(byteBuffer.array(), 0, byteBuffer.limit()));
                    byteBuffer.clear();
                }
            }
            it.remove();
        }
    }
}
